// pages/venue/city.js
const api = require('../../utils/api');

Page({
  data: {
    currentCity: '',
    cities: [],
    hotCities: [],
    allCities: [],
    searchKeyword: '',
    loading: true
  },

  onLoad: function(options) {
    // 获取当前选择的城市
    const currentCity = wx.getStorageSync('currentCity') || '长沙';
    this.setData({
      currentCity: currentCity
    });
    
    // 加载城市数据
    this.loadCities();
  },
  
  // 加载城市数据
  loadCities: function() {
    this.setData({ loading: true });
    
    // 获取热门城市
    api.city.getHotCities()
      .then(res => {
        if (res.success && res.data && res.data.list) {
          this.setData({
            hotCities: res.data.list
          });
        }
      })
      .catch(err => {
        console.error('获取热门城市失败', err);
        wx.showToast({
          title: '获取热门城市失败',
          icon: 'none'
        });
      });
    
    // 获取所有城市
    api.city.getCityList()
      .then(res => {
        if (res.success && res.data && res.data.list) {
          this.setData({
            allCities: res.data.list,
            cities: res.data.list,
            loading: false
          });
        }
      })
      .catch(err => {
        console.error('获取城市列表失败', err);
        wx.showToast({
          title: '获取城市列表失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 搜索城市
  onInputSearch: function(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    
    // 如果有关键词，则过滤城市列表
    if (keyword) {
      const filteredCities = this.data.allCities.filter(city => {
        return city.name.indexOf(keyword) !== -1 || 
               (city.province && city.province.indexOf(keyword) !== -1);
      });
      this.setData({
        cities: filteredCities
      });
    } else {
      // 如果没有关键词，显示全部城市
      this.setData({
        cities: this.data.allCities
      });
    }
  },

  // 清空搜索
  onClearSearch: function() {
    this.setData({
      searchKeyword: '',
      cities: this.data.allCities
    });
  },

  // 选择城市
  onTapCity: function(e) {
    const cityName = e.currentTarget.dataset.name;
    wx.setStorageSync('currentCity', cityName);
    
    // 返回上一页
    wx.navigateBack({
      success: () => {
        // 通过事件通知上一页刷新数据
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('citySelected', { city: cityName });
        }
      }
    });
  },

  // 返回定位城市
  onTapBackToLocation: function() {
    // 实际应用中应该获取用户位置并解析城市
    // 这里简化为直接返回当前城市
    wx.navigateBack({
      success: () => {
        // 通过事件通知上一页刷新数据
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('citySelected', { city: this.data.currentCity });
        }
      }
    });
  },

  // 返回上一页
  onTapBack: function() {
    wx.navigateBack();
  }
});